﻿using System.Net;
using System.Text;
using RestSharp;

namespace StudyCompanion.Core.Web;

public class HttpMethods
{
    /// <summary>
    ///     发起POST异步请求
    /// </summary>
    /// <param name="url"></param>
    /// <param name="postData"></param>
    /// <param name="headers">填充消息头</param>
    /// <returns></returns>
    public static string HttpPostJson(string url, string postData = null, Dictionary<string, string> headers = null)
    {
        var encoding = Encoding.Default;
        var request = (HttpWebRequest)WebRequest.Create(url);
        request.Method = "post";
        request.Accept = "application/json";
        request.ContentType = "application/json";
        if (headers != null)
            foreach (var key in headers.Keys)
                request.Headers.Add(key, headers[key]);

        var buffer = Encoding.UTF8.GetBytes(postData);
        request.ContentLength = buffer.Length;
        request.GetRequestStream().Write(buffer, 0, buffer.Length);
        var response = (HttpWebResponse)request.GetResponse();
        using (var reader = new StreamReader(response.GetResponseStream(), encoding))
        {
            return reader.ReadToEnd();
        }
    }

    public static void HttpPost(string url, string content, Action<string> jsonAction)
    {
        var client = new RestClient($"{url}");
        client.Timeout = -1;
        var request = new RestRequest(Method.POST);
        request.AddHeader("Content-Type", "application/json");
        request.AddHeader("Accept", "application/json");
        request.AddHeader("Authorization",
            "Basic ODIzMDExYzlkMDcxNWZkYzY3YTRiYTg4OmJiMzU2ZTQwZTU0MmNkZmQ4ZmYzZTdmNA==");
        var body = "{" + "\"loginToken\"" + ":" + $"\"{content}\"" + "}";
        request.AddParameter("application/json", body, ParameterType.RequestBody);
        var response = client.Execute(request);
        jsonAction?.Invoke(response.Content);
    }
}